from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.urls import reverse

from .models import Question, Choice

def index(request):
    # 获取question数据，并按照pub_date倒序排序(-pub_date为降序，pub_date为升序)
    latest_question_list = Question.objects.order_by('-pub_date')[:10]
    context = {
        'latest_question_list': latest_question_list,
    }
    return render(request, 'apps/index.html', context)

def detail(request, question_id):
    # 通过 pk 来查询 Question
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'apps/detail.html', {'question': question})

def vote(request, question_id):
    # 通过question_id 获取 Question
    question = get_object_or_404(Question, pk=question_id)
    try:
        # 通过choice.id 获取 choice
        selected_choice = question.choice_set.get(pk=request.POST.get('choice', -1))
    except (KeyError, Choice.DoesNotExist) as e:
        # 异常处理
        return render(request, 'apps/detail.html', {'question': question, 'error_message': '请选择选项'})
    else:
        # votes 加1 并保存
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('apps:results', args=[question.id,]))


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'apps/results.html', {'question': question})